package scau.zzf.base.aop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by zzf on 2017/5/25.
 */
public class BindingResultAop {
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        BindingResult bindingResult = null;

        if (isValidServiceMethodForTx(joinPoint.getSignature().getName())) {
            for(Object arg:joinPoint.getArgs()){
                if(arg instanceof BindingResult){
                    bindingResult = (BindingResult) arg;
                }
            }

            if(bindingResult.hasErrors()){

                StringBuilder msg = new StringBuilder();
                for(ObjectError error :bindingResult.getAllErrors()){
                    msg.append(error.getDefaultMessage());
                    msg.append("\n");
                }
                Map map = new HashMap<>();
                map.put("statusCode", 0);
                map.put("statusMsg", msg.toString());

                return map;
            }
        }

        return joinPoint.proceed();
    }


    private Boolean isValidServiceMethodForTx(String methodName){
        if(methodName.startsWith("va")){
            return true;
        }
        return false;
    }
}
